var DBFactory = require('../db/mysql_db');
var positionDao = module.exports;

positionDao.list = function(data, cb) {
    var sql = 'select * from mechanism_position as mp left join mechanism as m on m.id = mp.mechanism_id where 1 ';
    var sql_total = 'select count(*) as count from mechanism_position as mp left join mechanism as m on ' +
        ' m.id = mp.mechanism_id where 1 ';
    var arr = [];
    if(data.id) {
        sql += ' and mp.id = ? ';
        sql_total += ' and mp.id = ? ';
        arr.push(data.id);
    }
    if(data.mechanism_name) {
        sql += ' and m.mechanism_name like ? ';
        sql_total += ' and m.mechanism_name like ? ';
        arr.push('%'+data.mechanism_name+'%');
    }
    DBFactory.executeSql(sql_total, arr, 'getMechanismListTotal', function(err, total) {
        if(err) return cb(err);
        DBFactory.executeSql(sql, arr, 'getMechanismList', function(e, result) {
            if(e) return cb(e);
            sql += ' limit ?, ? ';
            arr.push(data.start);
            arr.push(data.size);
            cb(null, {total: total[0].count, data: result});
        })
    })
}

function doSave(data, cb) {
    var position = {};
    ['id', 'mechanism_id', 'course_id', 'telephone', 'tel_name', 'address', 'end_date',
        'lon', 'lat'].forEach(function(m) {
        if(data[m]) position[m] = data[m];
    })
    var sql = 'replace into mechanism_position set ? ';
    DBFactory.executeSql(sql, position, 'mechanismPositionSave', function(err, result) {
        if(err) return cb(err);
        if(!data.id) {
            data.mp_id = result.insertId;
            updateAuth(data);
        }
        cb(null, '设置成功！');
    })
}
function updateAuth(data) {
    var sql = 'update auth set mp_id = ?, course_id = ?, is_used = 1 where id = ? ';
    DBFactory.executeSql(sql, [data.mp_id, data.course_id, data.auth_id], 'updateAuth', function(err, result) {
        if(err) console.log(err);
    })
}
function canAdd(data, cb) {
    var sql = 'select id, duration from auth where openid = ? and is_used = 0 limit 1 ';
    DBFactory.executeSql(sql, [data.openid], 'canAdd', function(err, result) {
        if(err) return cb(err);
        if(result && result.length > 0) {
            data.auth_id = result[0].id;
            var now = new Date();
            data.end_date = new Date(now.setDate(now.getDate() + parseInt(result[0].duration)));
            doSave(data, cb);
        } else {
            cb(new ERR('无权限,请先购买地址权限！', 401));
        }
    })
}
function getAuthInfo(data, cb) {
    var sql = 'select * from auth where mp_id = ? ';
    DBFactory.executeSql(sql, [data.id], 'getAuthInfo', function(err, result) {
        if(err) return cb(err);
        if(result.length > 0) {
            data.course_id = result[0].course_id;
            doSave(data, cb);
        } else {
            cb(new ERR('编辑地址错误,请重试！！', 401));
        }
    })
}
positionDao.save = function(data, cb) {
    if(!data) return cb(new ERR(500));
    if(!data.id) {
        canAdd(data, cb);
    } else {
        getAuthInfo(data, cb);
    }
}

function addAuth(data, cb) {
    var auth = [];
    auth.push(data.openid);
    auth.push(data.duration);
    auth.push(0);
    auth.push(0);
    auth.push(0);
    auth.push(0);
    var auths = [];
    for(var i=1; i<=data.num; i++) auths.push(auth);
    var sql = 'insert into auth(`openid`,`duration`,`course_id`,`mechanism_id`,`is_used`,`mp_id`) values ? ';
    DBFactory.executeSql(sql, [auths], 'addAuth', function(err) {
        if(err) return cb(err);
        log(data,cb);
    })
}
function log(data,cb) {
    var log = {};
    log.pi_id = 0;
    log.type = 2;
    log.cost = data.pay_amount;
    log.duration = data.duration;
    log.openid = data.openid;
    var sql = 'insert into purchase_log set ? ';
    DBFactory.executeSql(sql, log, 'log', function(err) {
        if(err) return cb(err);
        cb(null, 'success!');
    })
}
positionDao.grant = function(data, cb) {
    addAuth(data, cb);
}

positionDao.addrManage = function(data, cb) {
    if(!data) return cb(new ERR(500));
    var sql = 'select * from mechanism_position where mechanism_id = ? ';
    DBFactory.executeSql(sql, [data.mechanism_id], 'addrManage', function(err, result) {
        if(err) return cb(err);
        cb(null, result);
    })
}

